package com.quanquan.store.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.quanquan.store.alipay.request.PayNotifyModle;
import com.quanquan.store.dto.KetopVipDTO;
import com.quanquan.store.request.AlipayRequest;
import com.quanquan.store.request.KetopVipRequest;
import com.quanquan.store.request.WxPayRequest;
import com.quanquan.store.service.WxPayService;
import enums.ResCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import utils.PayUtils;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.quanquan.store.alipay.Alipay;
import com.quanquan.store.alipay.request.PayNotifyModle;
import com.quanquan.store.dto.KetopParkingRecordDTO;
import com.quanquan.store.dto.KetopVipDTO;
import com.quanquan.store.request.AlipayRequest;
import com.quanquan.store.request.FreeDetail;
import com.quanquan.store.request.KetopVipRequest;
import com.quanquan.store.request.PayParkingFeeRequest;
import com.quanquan.store.service.WxPayService;
import com.quanquan.store.shenxinpay.ShenXinPay;
import com.quanquan.store.shenxinpay.enitiy.request.NotifyModle;
import com.quanquan.store.shenxinpay.enitiy.request.NotifyRequest;
import com.quanquan.store.shenxinpay.enitiy.request.UseCoupon;
import commond.IntegralOutPut;
import enums.ResCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import utils.Request;
import utils.StringUtil;
import utils.StringUtils;
import web.response.ResultBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author:lihonglinag
 * @date:2020-01-09 21:28
 * @version:v 1.0.0
 */


@Controller
@RequestMapping("/alipay")
public class AlipayController {

    private static Logger logger = LoggerFactory.getLogger(AlipayController.class);

    @Autowired
    private WxPayService wxPayService;

    @Value("${module-url.parkingUrl}")
    private String parkingUrl;


    @Autowired
    private Alipay alipay;
    /**
     * 生成预订单
     *
     * @param
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/create_parking_order")
    @ResponseBody
    public ResultBody createParkingOrder(@RequestBody AlipayRequest alipayRequest) {
        String page= wxPayService.createParkingOrder(alipayRequest);
        if (StringUtil.isEmpty(page)) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
        return new ResultBody(ResCodeEnum.CUSTOM.getCode(), ResCodeEnum.CUSTOM.getMsg(), page);
    }


    @RequestMapping("/getUserId")
    public String getUserId(HttpServletRequest request, String auth_code, String redirect) {
        StringBuffer redUrl = new StringBuffer().append("redirect:");
        if (StringUtils.isEmpty(auth_code)) {
            String localurl = new StringBuffer().append(request.getScheme()).append("://")
                    .append("huanlegang.quanquankeji.cn/quanquan-store/")
                    .append(request.getRequestURI()).append("?").append(request.getQueryString()).toString();
            redUrl.append(alipay.createOauthUrlForCode(localurl));
        } else {
            logger.info("auth_code:{}",auth_code);
            AlipaySystemOauthTokenResponse oauthToken = null;
            try {
                oauthToken = alipay.getOauthToken(auth_code);
                redirect = URLDecoder.decode(redirect, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            redUrl.append(redirect);
            if (redirect.contains("?")) {
                redUrl.append("&");
            } else {
                redUrl.append("?");
            }
            if (oauthToken != null){
                redUrl.append("userid=").append(oauthToken.getUserId());
            }
        }
        logger.info("redirect:{}",redUrl);
        return redUrl.toString();

    }

    @RequestMapping(path = "/payNotify", method = RequestMethod.POST)
    @ResponseBody
    public String payNotify(@RequestBody NotifyModle notifyRequest) {
        logger.info("postJosn 回调停车支付返回值：{}", JSON.toJSONString(notifyRequest));
        if(!"S".equalsIgnoreCase(notifyRequest.getTrade_status())) {
            return "ERROR";
        }
        String outTradeNo = notifyRequest.getOut_order_id();
        String transactionId = notifyRequest.getChnl_order_id();

        PayParkingFeeRequest payParkingFeeRequest = new PayParkingFeeRequest();
        payParkingFeeRequest.setOrderNo(outTradeNo);
        String postJson = Request.postJson(parkingUrl + "/ketop_parking/query_by_parking_order_num", payParkingFeeRequest);

        JSONObject jsonObject = JSON.parseObject(postJson);
        if (null == jsonObject) {
            return "ERROR";
        }
        Integer resCode = jsonObject.getInteger("resCode");
        KetopParkingRecordDTO data = new KetopParkingRecordDTO();
        if (0 == resCode) {
            data = jsonObject.getJSONObject("data").toJavaObject(KetopParkingRecordDTO.class);
        }

        Integer priceD = data.getTotalFee() - data.getTotalFreeFee();
        String price = String.valueOf(priceD.intValue());
        //同步停车数据
        PayParkingFeeRequest parkingRecordRequest = new PayParkingFeeRequest();
        parkingRecordRequest.setOrderNo(outTradeNo);
        parkingRecordRequest.setTransactionId(transactionId);
        parkingRecordRequest.setAmount(data.getTotalFee() - data.getTotalFreeFee());
        parkingRecordRequest.setDiscount(0);
        parkingRecordRequest.setFreeMoney(data.getTotalFreeFee());
        parkingRecordRequest.setFreeTime(0);
        List<FreeDetail> freeDetails = new LinkedList<>();
        FreeDetail freeDetail = new FreeDetail();
        freeDetail.setType(0);
        freeDetail.setMoney(data.getTotalFreeFee());
        freeDetail.setTime(0);
        freeDetail.setCode(data.getUserId());
        freeDetails.add(freeDetail);
        parkingRecordRequest.setFreeDetail(freeDetails);
        if (data.getTotalFreeFee() > 0) {
            Request.postJson(parkingUrl + "/ketop_parking/get_payment_recharge", parkingRecordRequest);
        } else {
            Request.postJson(parkingUrl + "/ketop_parking/pay_parking_fee", parkingRecordRequest);
        }
        System.out.println("支付宝 支付回调数据结束");
        return "SUCCESS";

    }

    /**
     * 微信服务器通知java后端（科拓vip）
     *
     * @param
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/wx_ketop_vip_notify")
    @ResponseBody
    public String wxKetopVipNotify(PayNotifyModle payNotifyModle, HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        System.out.println("支付宝回调：out_trade_no:{}"+payNotifyModle.getOut_trade_no());
        if (StringUtils.isEmpty(payNotifyModle.getOut_trade_no())
                || StringUtils.isEmpty(payNotifyModle.getNotify_type())) {
            return "fail";
        }
        String notify_type = payNotifyModle.getNotify_type();
        String trade_status = payNotifyModle.getTrade_status();
        if ("wait_buyer_pay".equalsIgnoreCase(notify_type.trim().toLowerCase())) {
            return "success";
        }
        if (!"TRADE_SUCCESS".equalsIgnoreCase(trade_status.trim().toLowerCase())
                && !"TRADE_FINISHED".equalsIgnoreCase(trade_status.trim())) {
            return "success";
        }

        String outTradeNo = payNotifyModle.getOut_trade_no();
        String transactionId = payNotifyModle.getTrade_no();

            KetopVipRequest payParkingFeeRequest = new KetopVipRequest();
            payParkingFeeRequest.setOrderNo(outTradeNo);
            String postJson = Request.postJson(parkingUrl + "/ketop_vip/get_order_by_order_no", payParkingFeeRequest);

            JSONObject jsonObject = JSON.parseObject(postJson);
            if (null == jsonObject) {
                return null;
            }
            String price = "";
            Integer resCode = jsonObject.getInteger("resCode");
            KetopVipDTO data;
            if (0 == resCode) {
                data = jsonObject.getJSONObject("data").toJavaObject(KetopVipDTO.class);
                Integer priceD = data.getFee();
                price = String.valueOf(priceD.intValue());
                Request.postJson(parkingUrl + "/ketop_vip/update_ketop_vip", payParkingFeeRequest);
            }
        System.out.println("支付宝 支付回调数据结束");
        return "success";
    }
}
